var fs = require('fs');
var path = require('path');
function readFile(filename) {
  return fs.readFileSync(path.join(__dirname, filename), 'utf-8');
}
var last = Date.now();
var config = {};

function refreshConfig() {
  if (Date.now() - last < 1000) {
    last = Date.now();
    return;
  }
  last = Date.now();
  config = JSON.parse(readFile('config.js'));
}

function parsePattern(pattern) {
  if (
    pattern.indexOf('/') == 0 && 
    (
      pattern.lastIndexOf('/') == pattern.length - 1 ||
      pattern.lastIndexOf('/') == pattern.length - 2
    )
  ) {
    return eval('(' + pattern + ')');;
  }
  return {test: t => t.indexOf(pattern) > -1 };
}

refreshConfig();

module.exports = {
  shouldInterceptHttpsReq: function () {
    return true;
  },
  replaceServerResDataAsync: function(req,res,serverResData,callback) {
    refreshConfig();
    var configs = config['replace-res'] || [];
    for (let config of configs) {
      var pattern = parsePattern(config.pattern);
      if (pattern.test(req.url)) return callback(config.content);
    }
    callback(serverResData);
  },
  shouldUseLocalResponse : function(req,reqBody){
    refreshConfig();
    var configs = config['return-direct'] || [];
    for (let config of configs) {
      var pattern = parsePattern(config.pattern);
      if (pattern.test(req.url)) {
        console.log(req.url + ' matched ' + config.pattern);
        req.R_BODY = config.content;
        return true;
      }
    }
    return false;
  },
  dealLocalResponse : function(req,reqBody,callback){
    var b = req.R_BODY || '[empty]';
    var h = {"content-type": 'text/html'};
    if (b.indexOf('{') == 0) h = {"content-type":"application/json;charset=utf-8"};
    callback(200, h, b);
  }
};
